package com.bai.localshop.task;

import com.bai.localshop.mapper.OrderMapper;
import com.bai.localshop.pojo.entity.Order;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

import static com.bai.localshop.constant.SystemConstants.*;

/**
 * 定时任务类，处理订单状态
 */
@Component
@RequiredArgsConstructor
public class OrderTask {
    private final OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟处理一次
    public void processTimeoutOrder() {
        //获取到1分钟前的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-1);
        //获取到超时订单列表
        List<Order> orderList = orderMapper.getByStatusAndOrderTimeLT(ORDER_PENDING_PAYMENT, time);
        if (orderList != null && !orderList.isEmpty()) {
            orderList.forEach(each->{
                try {
                    each.setStatus(ORDER_CANCELLED);
                    each.setCancelReason("订单超时未付款，自动取消");
                    each.setCancelTime(LocalDateTime.now());
                    each.setUpdateTime(LocalDateTime.now());
                    orderMapper.updateById(each);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
}
